<?php
/**
 * Created by PhpStorm.
 * User: xuke
 * Date: 16/6/21
 * Time: 下午2:29
 */

namespace App\Http\Model;
use App\Exceptions\ApiException;

class OrderSub extends Base
{

    public $table = 'order_sub';

    public $timestamps = false;

    protected $guarded = [
        'order_sub_id'
    ];

    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id', 'order_id');
    }

    public function provider()
    {
        return $this->belongsTo(Provider::class, 'provider_id', 'provider_id');
    }

    public function order_goods()
    {
        return $this->hasMany(OrderGoods::class, 'order_sub_id', 'order_sub_id');
    }

    public function setDefault()
    {
        $this->create_at = date('Y-m-d H:i:s');
        return $this;
    }

    /**设置供应商
     * @param $provider
     * @return $this
     * @throws ApiException
     */
    public function setProvider($provider)
    {
        if (is_numeric($provider))
        {
            $provider = Provider::find($provider);
        }else if(!$provider instanceof Provider)
        {
            throw new ApiException(-2, '供应商不存在');
        }
        $this->provider_id = $provider->provider_id;
        return $this;
    }

    /**设置主订单
     * @param $order
     * @return $this
     * @throws ApiException
     */
    public function setOrder($order)
    {
        if (is_numeric($order))
        {
            $order = Order::find($order);
        }else if(!$order instanceof Order)
        {
            throw new ApiException(-2, '订单不存在');
        }
        $this->order_id = $order->order_id;
        return $this;
    }
}